package com.zzjson.aop.aspect.program.proxyfactory;

import com.zzjson.aop.model.Member;
import com.zzjson.aop.service.IMemberService;
import com.zzjson.aop.service.MemberService;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
import org.springframework.aop.support.RegexpMethodPointcutAdvisor;

/**
 * <p>****************************************************************************</p>
 * <li>Description : TODO </li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2021年02月19日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class ProxyFactoryDemo {
	public static void main(String[] args) {
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(new MemberService());

		proxyFactory.addInterface(IMemberService.class);
		//proxyFactory.setTargetClass(IMemberService.class);

		//直接使用Advice
		customAdvice(proxyFactory);

		//基于名称匹配的Advisor
		//nameMatch(proxyFactory);

		//基于正则匹配的Advisor
		//RegexpMatch(proxyFactory);

		IMemberService memberService = (IMemberService) proxyFactory.getProxy();
		memberService.get();

		memberService.save(new Member());

	}

	private static void RegexpMatch(ProxyFactory proxyFactory) {
		RegexpMethodPointcutAdvisor regexpMethodPointcutAdvisor = new RegexpMethodPointcutAdvisor();
		regexpMethodPointcutAdvisor.setAdvice(new MethodBeforeLogAdvice());
		regexpMethodPointcutAdvisor.setPattern("com.zzjson.aop.service.*");
		proxyFactory.addAdvisor(regexpMethodPointcutAdvisor);
	}

	private static void customAdvice(ProxyFactory proxyFactory) {
		proxyFactory.addAdvisor(new Advisor() {
			@Override
			public Advice getAdvice() {
				return new MethodBeforeLogAdvice();
			}

			@Override
			public boolean isPerInstance() {
				return true;
			}
		});
	}

	private static void nameMatch(ProxyFactory proxyFactory) {
		NameMatchMethodPointcutAdvisor nameMatchMethodPointcutAdvisor = new NameMatchMethodPointcutAdvisor();
		nameMatchMethodPointcutAdvisor.addMethodName("save");
		nameMatchMethodPointcutAdvisor.setAdvice(new MethodBeforeLogAdvice());

		proxyFactory.addAdvisor(nameMatchMethodPointcutAdvisor);
	}

}